import { useEffect, useState, forwardRef } from 'react';
import { Button, Input, Form, Select, Skeleton, App } from 'antd';
import loadable from '@loadable/component';

import { getWorkList } from '@/service/api';
import { UPLOAD_FILE_OSS } from '@/config/url';

import styles from './index.module.scss';

const CommonUploadFiles = loadable(() => import('@/components/CommonUploadFiles'), {fallback: <Skeleton active/>});
const FormTag = loadable(() => import('@/components/FormTag'));

export default forwardRef((props, ref) => {
    const { onCancel, onOk, isModal=false, submitting=false } = props;
    const initState = () => ({
        workList: [],
        imgUploading: false,
    });
    const [state, setState] = useState(initState);
    const [form] = Form.useForm();
    const { message } = App.useApp();

    // 作品列表
    const fetchWorkList = async () => {
        const [res, err] = await getWorkList({pageNo: 1, pageSize: 9999});
        const workList = (res?.data?.records || []).map(item => ({value: item.seriesName, label: item.seriesName}));
        setState(o => ({...o, workList}));
    };
    // 作品筛选
    const onWorkSearch = (input, option) => {
        if (!input) return true;
        return option.label.toLowerCase().includes(input.toLowerCase());
    };
    // 返回
    const goBack = () => {
        onCancel?.();
    };

    // 新建角色，新建成功后返回首页
    const onSubmit = async () => {
        message.destroy();
        if (state.imgUploading) {
            message.warning('请等待图片上传完成');
            return;
        }
        form.validateFields().then(async values => {
            onOk?.(values);
        });
    };

    useEffect(() => {
        fetchWorkList();
    }, []);

    return (
        <div className={styles['container']}>
            <Form
                form={form}
                layout="horizontal"
                labelWrap={true}
                colon={false}
                labelCol={{span: 3}}
                wrapperCol={{span: 20}}
                ref={ref}
            >
                <h3 className={styles['base']}>基本信息</h3>
                <Form.Item
                    name="charactarImages"
                    label="图片"
                    rules={[
                        { 
                            required: true, 
                            validator: (_, value) => {
                                if (!value || !value.images || value.images.length === 0) {
                                    return Promise.reject(new Error('请上传角色图片'));
                                }
                                return Promise.resolve();
                            }
                        }
                    ]}
                    labelCol={{span: isModal?4:2}}
                    wrapperCol={{span: 20}}
                >
                    <CommonUploadFiles
                        enableMainImage
                        accept="image/*"
                        onUploadingChange={flag => setState(o => ({ ...o, imgUploading: !!flag }))}
                        buttonText="上传图片"
                    />
                </Form.Item>
                <Form.Item
                    name="charactarName"
                    label="角色名"
                    rules={[{ required: true, message: '请输入角色名' }]}
                    labelCol={{span: isModal?4:2}}
                    wrapperCol={{span: 20}}
                >
                    <Input placeholder="请输入角色名" maxLength={64} showCount />
                </Form.Item>
                <Form.Item
                    name="seriesNames"
                    label="所属作品"
                    labelCol={{span: isModal?4:2}}
                    wrapperCol={{span: 20}}
                >
                    <Select
                        placeholder="选择所属作品"
                        showSearch
                        filterOption={onWorkSearch}
                        options={state.workList || []}
                        mode="tags"
                    />
                </Form.Item>
                <Form.Item
                    name="searchNames"
                    label="检索名称"
                    labelCol={{span: isModal?4:2}}
                    wrapperCol={{span: 20}}
                >
                    <FormTag placeholder="添加检索名称" maxLength={64} />
                </Form.Item>

                {/* 提交 */}
                <Form.Item noStyle>
                    <div className={styles['footer']}>
                        <Button onClick={goBack} disabled={submitting}>返回</Button>
                        <Button onClick={onSubmit} type="primary" htmlType="submit" loading={submitting} disabled={submitting || state.imgUploading}>提交</Button>
                    </div>
                </Form.Item>
            </Form>
        </div>
    )
});
